package com.zyj.classic;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreTest {
    public static void main(String[] args) throws InterruptedException {
        //相当于厕所5个坑, 每个坑位一个线程
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    semaphore.acquire();//进坑; 如果坑不够了, 就等着, 别人让出坑位, 你们所有等坑的竞争进坑
                    System.out.println("semaphore availablePermits = " + semaphore.availablePermits()); //打印坑位数量
                    System.out.println("do " + finalI);
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    semaphore.release();//出坑
                } catch (Exception e) {
                }
            }).start();
        }

        TimeUnit.SECONDS.sleep(100);

    }
}
